package org.goyo.main.services.system.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.Pager;
import org.goyo.main.domain.dao.system.ISysRoleDao;
import org.goyo.main.domain.dao.system.ISysRoleResourceDao;
import org.goyo.main.domain.entity.system.SysRole;
import org.goyo.main.domain.entity.system.SysRoleResource;
import org.goyo.main.services.system.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysRoleServiceImpl implements ISysRoleService {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ISysRoleDao sysRoleDao;
	@Resource
	private ISysRoleResourceDao sysRoleResourceDao;
	
	
	@Override
	public void delByUuids(Object[] uuids) throws DBException, ServiceException {
		//删除角色表
		sysRoleDao.delBatch(SysRole.class, "uuid", uuids);
		//删除角色资源表
		sysRoleResourceDao.delBatch(SysRoleResource.class, "roleId", uuids);;
	}

	@Override
	public SysRole findByUuid(String uuid) throws DBException, ServiceException {
		return sysRoleDao.get(SysRole.class, uuid);
	}

	@Override
	public String saveOrUpdateInfo(SysRole info) throws DBException,
			ServiceException {
		
		String uuid = info.getUuid();
		//删除角色资源表
		if(uuid != null &&  !"".equals(uuid)){
			sysRoleResourceDao.delBatch(SysRoleResource.class, "roleId", new String[]{uuid});
			sysRoleDao.update(info);
			sysRoleDao.flush();
		}else{
			uuid = sysRoleDao.save(info);
		}
		
		String ids = info.getResourcesIds();
		if(ids != null){
			String [] ida = ids.split(",");
			for(int i=0;i<ida.length;i++){
				SysRoleResource roleResource = new SysRoleResource();
				roleResource.setRoleId(uuid);
				roleResource.setResourceId(ida[i]);
				sysRoleResourceDao.save(roleResource);
			}
		}
		return uuid;
	}

	@Override
	public Pager<SysRole> findByCondition(String cond, Pager pager)
			throws DBException, ServiceException {
		return  sysRoleDao.findByCond(cond, pager);
		/*int total = sysRoleDao.findByCondCount(cond);
		pager.setList(list);
		pager.setCount(total);
		return pager;*/
	}

  @Override
  public String getRoleSerialNumber() throws DBException, ServiceException {
    int i =0;
    try {
      List list =  sysRoleDao.findObjects("select max(CAST(roleNum AS  int)) from SysRole", null, null);
      if(null!=list){
       i =(Integer)list.get(0)+1;
      }
    } catch (Exception e) {
      i=0;
      logger.error(e.getMessage(),e);
    }
    String pattern="0000";
    java.text.DecimalFormat df = new java.text.DecimalFormat(pattern);
    return df.format(i)+"";
  }
}
